<?php
$systemUser = 'sudo -Hu www';
$rootPath = '/www/web/';
$fatherPath = 'public_html';

$requestBody = file_get_contents("php://input");
$content = json_decode($requestBody, true);
$resName = $content['project']['name'];
$logPath = $resName.'_my_zhangyuelei_com';

$noCreate = array('hook','test');

if (in_array($resName, $noCreate)) {
    die('no create');
}

if (empty($requestBody) || empty($resName)) {
    die('send fail');
}
if (!is_dir('log')) {
    mkdir('log');
}
$savePath =$rootPath.$logPath.'/'.$fatherPath;

$AllGitClone = json_decode(file_get_contents('AllGitClone.txt'), true);
$isClone = in_array($resName, $AllGitClone);
if (!empty($AllGitClone) && $isClone) {
        
    if ($content['ref']=='refs/heads/master' && $content['total_commits_count']>0) {
        $res_log = '-------------------------'.PHP_EOL;
        $res_log .= $content['user_name'] . ' 在' . date('Y-m-d H:i:s') . '向' . $resName . '项目的' . $content['ref'] . '分支push了' . $content['total_commits_count'] . '个commit：'.$content['after'];
        $res_log .= PHP_EOL."pull start --------".PHP_EOL;
        $sshUrl = "cd {$savePath} && {$systemUser} git pull";
        $res_log .= shell_exec($sshUrl);//拉去代码
        $res_log .= "执行：$sshUrl".PHP_EOL;
        $res_log .= "pull end --------".PHP_EOL;
        file_put_contents("./log/".$logPath.'.log', $res_log, FILE_APPEND);
        die('pull success');
    }
}else{
    $resUrl = $content['project']['git_ssh_url'];
    $res_log = PHP_EOL."git clone start --------".PHP_EOL;
    $sshUrl = "cd {$savePath} && rm -rf * && cd .. && {$systemUser}  git clone {$resUrl} {$fatherPath}";
    $res_log .= shell_exec($sshUrl);
    $res_log .= date('Y-m-d H:i:s').'执行：'.$sshUrl.PHP_EOL;
    $res_log .= "git clone end --------".PHP_EOL;
    if (empty($AllGitClone)) {
        $AllGitClone = array($resName);
    }else{
        array_push($AllGitClone, $resName);
    }
    $AllGitClone = json_encode($AllGitClone);
    file_put_contents('AllGitClone.txt', $AllGitClone);
    file_put_contents("./log/".$logPath.'.log', $res_log, FILE_APPEND);
    die('clone success');


}
